<?php
class Gallery_GalleryController extends Promotor_Controller_Action_Scaffold {
	
	public $skin = array(
		// forsuje domyslny template i style na admin
		'template' => 'admin',
		'style' => 'default',
		// layout
		'layout' => 'admin_gallery',
		// rozszerzam konfiguracje
		'config' => array(
			'filename' => 'backend_config.ini'
		),

		// specjalizuje template dla akcji
		'index' => array(
			'layout' => 'gallery_index'
		)
	);
	
	public $acl = array(
		'list' => 'list',
		'add' => 'create',
		'edit' => 'update',
		'display' => 'show',
		'delete' => 'delete'
	);
	
	public $ajaxable = array(
		'list' => array('dojo'),
		'display' => array('html')
	);

	/**
	 * @see Promotor_Controller_Action_Scaffold specialization
	 */
	protected $_modelClass = 'Gallery_Model_Gallery';
	protected $_formAddClass = 'Gallery_Form_GalleryAdd';
	protected $_formEditClass = 'Gallery_Form_GalleryEdit';
	protected $_formRemoveClass = 'Gallery_Form_GalleryRemove';
	
	protected $_addPostObservableName = 'gallery_add_post';
	protected $_editPostObservableName = 'gallery_edit_post';
	protected $_deletePostObservableName = 'gallery_delete_post';
	
	public function init() {
		new Zend_Controller_Action_Helper_ContextSwitch();
		$ajaxContext = $this->_helper->getHelper('AjaxContext');
		if (!$ajaxContext->hasContext('dojo')) {
			$ajaxContext->addContext('dojo', array(
				'suffix' => 'dojo',
				'headers'   => array('Content-Type' => 'application/json'),
			));
		}
        $ajaxContext->initContext();
	}

	/**
	 * @return void
	 */
	public function indexAction() {
		$model = new Gallery_Model_Gallery();
		$this->view->rowset = $model->fetchAllInlineCache();		
	}

	/**
	 * @return void
	 */
	public function listAction() {
		$model = new Gallery_Model_Gallery();
		$table = $model->getDbTable();

		$rq = $this->getRequest();
		// via AJAX ..
		if ($rq->isXmlHttpRequest()) {
			$this->view->rowset = $model->fetchAll();
			return;
		} else
		if ($rq->isPost()) {
			switch ($rq->getPost('action_type')) {
				case 'update':
					if (null !== $rq->getPost('editable')) {
						if ($this->_helper->acl->isAllowed('update')) {
							$data = $rq->getPost('editable');
							$model->editableUpdate($data);
							$this->_helper->flashMessenger($model->getStatus());
						}
					}
					break;
				case 'delete':
					if (null !== $rq->getPost('action_checked')) {
						if ($this->_helper->acl->isAllowed('delete')) {
							$data = $rq->getPost('action_checked');
							$model->editableDelete($data);
							$this->_helper->flashMessenger($model->getStatus());
						}
					}
					break;
			}
			$this->_helper->redirector->goToUrlAndExit(getenv('HTTP_REFERER'));
			return;
		}

		// setup data grid
		$config = $this->_helper->config('gallery.xml');
		$grid = KontorX_DataGrid::factory($table, $config->grid);
		$grid->setValues($this->_getAllParams());
		
		$this->_setupDataGridPaginator($grid);

		$this->view->grid = $grid;
	}
}